package com.xiashitech.agent.service.extloadproxy;

import com.xiashitech.agent.cache.classloader.ClassLoaderCache;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.db.entity.DataWaterMarkConfig;
import com.xiashitech.agent.db.entity.DesensitiseRule;
import com.xiashitech.agent.db.entity.UserPermission;

import java.util.List;

public class AuthQueryServiceProxy {

    private static String className = AuthQueryServiceProxy.class.getName().substring(0,AuthQueryServiceProxy.class.getName().length() - 5).replace("extloadproxy","extload");

    /**
     * 代理AuthQueryService类的queryPermissions方法
     * @param userId
     * @param schemaName
     * @param tableName
     * @param operate
     * @return
     */
    public static List<UserPermission> queryPermissions(String userId, String schemaName, String tableName, String operate) {
        try {
            Class authQueryServiceClass = ClassLoaderCache.getLaunchClassLoader().loadClass(className);
            Object authQueryServiceInstance = authQueryServiceClass.getMethod("getInstance").invoke(null);
            return (List<UserPermission>)authQueryServiceClass.getMethod("queryPermissions", String.class, String.class, String.class, String.class).invoke(authQueryServiceInstance,userId,schemaName,tableName,operate);
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return null;
    }

    /**
     * 代理AuthQueryService类的queryDesensitizeInfo方法
     * @param schemaName
     * @param tableName
     * @param colName
     * @return
     */
    public static List<DesensitiseRule> queryDesensitizeInfo(String schemaName, String tableName, String colName) {
        try {
            Class authQueryServiceClass = ClassLoaderCache.getLaunchClassLoader().loadClass(className);
            Object authQueryServiceInstance = authQueryServiceClass.getMethod("getInstance").invoke(null);
            return (List<DesensitiseRule>)authQueryServiceClass.getMethod("queryDesensitizeInfo", String.class, String.class, String.class).invoke(authQueryServiceInstance,schemaName,tableName,colName);
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return null;
    }

    /**
     * 根据apiPath查询水印配置信息,由于apiPath在数据库中唯一,所以有且仅有一条配置匹配
     * @param apiPath
     * @return
     */
    public static DataWaterMarkConfig findDataWaterMarkConfig(String apiPath) {
        try {
            Class authQueryServiceClass = ClassLoaderCache.getLaunchClassLoader().loadClass(className);
            Object authQueryServiceInstance = authQueryServiceClass.getMethod("getInstance").invoke(null);
            return  (DataWaterMarkConfig) authQueryServiceClass.getMethod("findDataWaterMarkConfig", String.class).invoke(authQueryServiceInstance, apiPath);
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return null;
    }
}
